by Ron Schwarz
In this chapter
VBScript programming consists largely of designing layouts, writing code that deals with properties, events, and methods. This chapter covers events. It contains a short tutorial on event programming, and a rundown on handling events generated by the Internet Explorer, HTML Intrinsic controls, and a few of the literally thousands of available ActiveX custom controls.
An event-driven environment, such as Microsoft Windows, allows the user to interact with applications in a manner entirely different from older procedural systems, which tended to force the user to respond to the software in a highly regimented action/reaction sequence.
When a user clicks or moves the mouse, strikes a key, or opens a document, events are generated. By intercepting these events, and associating program code with them, applications provide a flexible, responsive interface, without the constraints imposed by old style procedural programs.
VBScript provides a mechanism for dealing with events as they occur. If you're familiar with Visual Basic, you have a head start on coping with VBS event issues. However, there are some significant differences in how things are handled in VBS. Thanks to the differences between Web pages and VB applications, event handling is a bit more complex with VBS. Fortunately, the ActiveX Control Pad helps ease the bumps, and automates much of the process of declaring and installing objects.
In VB, you have the luxury of the code window and an editor that automatically keeps track of all possible events for all objects in your project. It also automatically creates perfect event procedure headers. When working with VBS, however, you have two choices: you can either work in Notepad or a similar simple editor (This means you have to know which objects generate which events, and how to manually create the appropriate headers for each, as required), or, you can work in the ActiveX Control Pad.
For popping in and out of simple scripts, you may find Notepad sufficient, but for any significant development, you'll definitely want to learn how to use the ActiveX Control Pad. In addition to making it easier to manage complex web pages, it also provides a visual, interactive "VB-like" IDE (Integrated Development Environment) which facilitates the creation and management of HTML Layout Pages. The HTML Layout Pages are a very close approximation of "real" VB programming, right down to the toolbox, mouse-driven control placement and sizing, and Properties window. About the only thing missing is the debugging features.
See Chapters 3-5, which cover the ActiveX Control Pad in detail.
VBS events can originate in the Internet Explorer, HTML Intrinsic controls, or ActiveX custom controls. ActiveX custom control event handling is closest to VB event handlingùthis is no surprise since ActiveX controls are also used in VB.
HTML Intrinsic controls are not all that different in usage; the main differences are in declaration syntax and event and property naming conventions.
Listing 18.1 gives you a typical VBScript event handler. If you've used VB before, you'll note that it's virtually identical to a VB event handle; the only exceptions are the HTML tags that mark the beginning and end of the script, and the event name (OnClick, rather than Click). You can, by the way, have many separate routines in a single script.
Listing 18.1 Typical Event Header
You may also want to experiment with alternative control header styles such as the FOR syntax, shown in Listing 18.2.
Listing 18.2 FOR Style Event Header
This syntax does away with VB-style event sub-procedures. You may notice the absence of either a Sub or End Sub line in the preceding script block. The code is VBS, but it's not part of a VBS procedureùit is invoked when the object declared with the FOR parameter fires the event described in the EVENT parameter.
The Internet Explorer Object Model consists of a hierarchy of objects, most of which provide events (see fig. 18.1). This chapter does not cover aspects of objects that do not pertain to events. These topics are covered in "The Internet Explorer Object Model," in Chapter 10, "Embedding Internet Explorer into your Application." (Objects that provide no events are mentioned here in passing, to allow continuity of the Object Model, so you will have a good perspective on where events fit into the general scope of the hierarchy.) The relationships between the different levels of the Object Model (to the extent that they involve event handling issues) are discussed in the following sections.
FIG. 18.1
Internet Explorer Object Model
The Window object has two events: OnLoad, and OnUnload. OnLoad fires when a page is loaded. Inline code (VBS code that is contained within <Script> blocks but outside any procedures) executes before the OnLoad event occurs, and may be a pseudo-event mimicking the Initialize event in VB. All inline code is affected, regardless of position. If multiple blocks of inline code exist in different locations within the page, they are executed first to last. After the last inline block finishes executing, the OnLoad event fires, and any associated code executes.
There is a significant distinction between inline code and OnLoad event code. Operations that change the content on the page, such as document.write method invocations, can only be performed with inline code since this code is executed as the page is being loaded, whereas the OnLoad event fires after the page has been loaded and formatted.
The OnUnload event is the counterpart to the OnLoad event. It is fired when the page is about to be unloaded.
The Frame object is an array of windows. It is covered in Chapter 2, "Review of HTML."
The History object exposes the Internet Explorer's History list (previous locations). It has no events.
The Navigator object contains information about the browser, similar to the App object in Visual Basic. It has no events.
The Location object has no events. However, changing its properties results in events being fired by the Window object as pages are unloaded and loaded.
The Script object is a collection of all scripts in the page. Because scripts are contained in the object hierarchy, they can be called from different windows by prefacing them with the name of the window that contains them, similarly to prefacing a procedure with a form or module name in VB. They expose no events.
The Document object provides no events. However, it serves as container for other objects that do fire events. (The Link, Anchor, and Form objects are contained in the Document object, and are described in the following sections.)
The Form object has one event: OnSubmit. When a form is submitted, the contents of the controls in the form are sent to the server. Immediately prior to sending them, the OnSubmit event fires, and be used to perform whatever validation is required, and cancel the submission if required. Unfortunately, at the time this book is going to press, OnSubmit is not yet functional using the pre-release tools available. This should be resolved by the time Internet Explorer 3.0 and VBScript are released.
The Link object contains a collection of all link-type anchors on the page. It provides MouseMove, OnMouseOver, and OnClick events for each link.The example in Listing 18.3 (LinkEvent.htm on the CD), demonstrates how to trap the MouseMove and OnClick Link events.
Listing 18.1 LINKEVENTS.HTMùLink Events Example
The LinkEvents example contains one Link, one Text control, one Timer, and a script. The Link is given a NAME property (MSLink), so that its events can be trapped by the event routines in the script.
The MSLink_OnClick event procedure will execute if the on-screen link is clicked. When it executes, it first displays a messagebox asking for confirmation. If you click the "No" button, you'll see another messagebox informing you that the Link can't be cancelled. The browser will then take you to the URL contained in the link. C'est la vie. (This event is actually usefulùfor cases where you need to perform "cleanup" code before leaving for the new URL.)
The MSLink_MouseMove event fires repeatedly as the mouse travels over the link. Three things are done here in this example: the Value property of the Text control is updated to reflect the fact that the mouse is moving over the Link, the Interval property of the Timer control is set to 0 to disable it, and then immediately reset to 250.
By setting the Interval to 0 and then 250, the Timer is stopped, and another 250 millisecond period begins; as long as the mouse keeps moving over the Link, the Timer will be continuously reset, and never fire its event. If the mouse stops moving, or moves off the Link, the MouseMove event will stop firing, and the Timer will time out, and fire its Timer event. At that point, the code in the tmrStoppedMoving_Timer event procedure will execute.
As this book goes to press, the OnMouseOver event is documented, but not implemented. If implemented, it will provide a simplified form of the MouseMove eventùit will be invoked the same way, but without any parameters.
Listing 18.2 IMGAST.HTMùImageMap Assistant Example
The ImageMap Assistant is a useful VBS application. Although it only uses 16 lines of VBS code, it solves a problem that vexes anyone creating image mapsùhow to determine coordinates for hotspots.
To use the ImageMap Assistant with your bitmaps, find the line
<a id="picXY" href=""><img src="events.bmp"></a>
Then, replace events.bmp with the name of your actual bitmap.
The MouseMove event is repeatedly fired as the mouse is moved over the link. The ImageMap Assistant example uses this event to periodically update the CurrentX and CurrentY textboxes.
The MouseMove event passes four parameters: Shift, Button, X, and Y. The Shift parameter returns a value indicating the state of the Shift, Ctrl, and Alt keys, according to the following table (See hard copy for the key icons):
Key | Shift Parameter | Value |
Shift | 1 | |
Ctrl | 2 | |
Alt | 4 |
You can test for a condition of multiple shift keys by "ANDing" the values. The following example code evaluates whether or not the Shift and Ctrl keys are pressed at the time the event occurs. (If none of the Shift keys are pressed, the Shift parameter returns 0.)
See Chapter 16, "VBScript Operators," for information on AND and other logical operators.
If ((Shift And 1) > 0) And ((Shift And 2) > 0) Then
End If
The Button parameter is similar in behavior to the Shift parameter; it returns a value indicating which, if any, mouse buttons were pressed when the event occurred.
You can test for multiple button press conditions using the same formula used with the MouseMove event, substituting the Button parameter for the Shift parameter.
The X and Y parameters return the position of the mouse pointer relative to the upper-left corner of the object. In the ImageMap Assistant example (this code fragment from IMGAST.HTM on the CD is shown in Listing 18.5), they are used to populate the CurrentX and CurrentY textboxes and to create the coordinate list. (The coordinate list is the list of the four numbersùstarting XY and ending XYùcontained in the txtHotspot Text control.)
The OnClick event occurs when the user clicks the left mouse button while the mouse pointer is over the object. It's a simple event, but is probably used more than all others combined. In the ImageMap Assistant, it's used to update the hotspot coordinates list.
Listing 18.5 IMGAST.HTMùOnClick Event Code
In this event Sub, you check to see if this is the first time the mouse is clicked. If it is, you replace anything in the hotspot coordinates textbox (txtHotspot) with the current X and Y values. Otherwise, you append them to the existing contents. After two clicks you have four values, which can be copied to the Clipboard and pasted into a VBS script. (You need to write additional VBS code to deal with the lists of hotspot coordinates, but that's the easy partùthe ImageMap Assistant code eliminates the tedium of trial and error guesswork when creating image maps.)
Figure 18.2 shows how the ImageMap Assistant will look when you load it into Internet Explorer.
ImageMap Assistant
The ImageMap Assistant will be invaluable when you're creating hotspots in imagemaps. For more information on imagemap issues, check out Chapter 11, "Designing VBScript Applications."
The Anchor Object has no events. It's mentioned here in passing, since it's part of the Object Model. For full coverage of the Object Model, see "The Internet Explorer Object Model," in Chapter 10, "Embedding Internet Explorer into Your Application."
The Form Object contains one event: OnSubmit. The OnSubmit event fires when a Form (an HTML form, not to be confused with a VB form) is submitted. There are two ways to submit a formùthe form's Submit method, and the use of a Submit HTML Intrinsic control. (As this book goes to press, the OnSubmit method is documented insofar as it is known that it will be available in the final release of IE 3.0, however, it is not yet implemented in the pre-release version, nor is VBScript syntax available.)
The Element Object is an array of all controlsùHTML and OBJECT (such as ActiveX)ùon a page. It's similar in concept to the Control Collection in Visual Basic. Because it's really just a series of pointers to "real" objects; it has no events of its own. For a full discussion of the Element Object, see "The Internet Explorer Object Model," in Chapter 10, "Embedding Internet Explorer into your Application."
VBS is able to detect events fired by the Intrinsic HTML and ActiveX controls. The main differences between using HTML controls and ActiveX controls involve declaration conventions and event names. (Control declaration issues are covered in other chapters.)
Hammers, Nails, and Platforms
Apart from usage differences, you may notice that HTML controls have a dearth of events when compared to most ActiveX controls. HTML, even when VBS-enabled, is not a full-fledged program development platform. VBS scripts are not complete applications. Automating Web pages is not the same as creating Visual Basic applications.
This is not by any means derogatory toward VBS. It's just a different animal. The axiom that says, "To a man with a hammer, everything looks like a nail," is something you need to keep in mind when developing script-enabled Web pages.
The ability to create HTML Layout Pages by using the ActiveX Control Pad does indeed make it possible to create real programs with VBS. Still, trying to do some things, such as accessing INI files or the registry, and using API calls require severe work-arounds in VBS.
So, sooner or later, you'll find a situation where what you really need is a comprehensive solution best provided by a Visual Basic application. Ideally, you'll make that discovery before you commit massive amounts of time and/or money developing Web pages for the project. And, there will be times when you'll experience the reciprocal of this principleùa simple Web page, brought to life with some concise, effective VBS code, is a life-saver.
The moral: Use the appropriate tool for each job.
If you use VB, you are familiar with the Click event; with HTML controls, it's the OnClick event. Similar differences with other event names are detailed in the following sections.
The Button control has one event: OnClick. This is functionally identical to the Click event in VB. When the user clicks the button, the event fires, and any associated event code is executed. The following example demonstrates use of the OnClick event with a Button control.
Like the Button control, the Checkbox control also has OnClick as its sole event. Checkboxes, like option buttons (called radio controls in HTML-speak), are frequently used without requirements for active processing at click-time. In many, if not most, cases, they are checked as the user requires, and when ready to proceed, a button is clicked telling the application to process the controls. At that point, all options are parsed and whatever action is required is taken.
However, there are also many situations in which you may need to perform processing when the user clicks an option. For instance, you may have mutually-exclusive or interlocking combinations of options. By testing at click-time, you can deal with input dynamically rather than all at once in a type of "batch mode."
Listing 18.8 (available on the CD as CHKEVENTS.HTM) demonstrates one such hypothetical example.
Listing 18.8 CHKEVENTS.HTMùCheckbox Events Example
Listing 18.8 demonstrates use of the CheckBox control's OnClick event. In this example, the user sees a list of four items, which can be selected in any combination. If the last item (All) is clicked, the DoAll routine in the VBS script checks all of the options.
The declaration for the chkAll HTML CheckBox control contains an OnClick="DoAll" clause. This causes the DoAll Sub procedure to replace the default (chkAll_OnClick, which is not used) event handler. This syntax can be useful when you want to have several controls use the same event handler.
The DoAll routine first tests whether or not the chkAll CheckBox is checked. If it is checked, the routine proceeds to check all three of the other CheckBoxes.
The Password Control is a specialized form of the Text control. It's used when you want the user to enter text without having the characters entered echo on screen. When a character is typed into a Password control, an asterisk ("*") is displayed.
The Password control has OnFocus and OnBlur events, like the Text control, but does not have OnChange or OnSelect events. For usage of the OnFocus and OnBlur events, see "Text and TextArea Control Events" earlier in this chapter.
At the time of this writing, the OnFocus and OnBlur events are documented, but not implemented for the Password control.
Radio Controls (hereinafter referred to by their "VB name" of OptionButtons), have one event: OnClick. Generally, you won't need to trap this event, as OptionButtons tend to be used for the purpose of determining one of a number of fixed selections. However, there are situations in which you may want to perform an action at the time a button is clicked. One example would be a quiz, where you want the victim (er, "student") to be unable to test the answer unless an answer was first selected. To accomplish this, it's necessary to be able to tell whether or not an OptionButton has been clicked. The example in Listing 18.9 (OptionEvents.htm on the CD) demonstrates such a situation.
Listing 18.3 OPTIONEVENTS.HTMùOptionButton Event Example
The example in Listing 18.9 uses four controlsùthree OptionButtons, a CommandButton, and Text:
The OptionButtons are all given the same name (optNum), which is what associates them as a group. In this example, they all use the same event handler (CanTest) although you can use different handlers for each of them if you require. (You can also use the default handlers, which for this example would have been optNum_OnClick.)
The CommandButton is named cmdTest, and the Text control is named txtStatus.
The script begins with a declaration of two Public variables:
Dim OkToTest, c
It's necessary to make these variables Public because they're used in more than one procedure. By declaring them outside of any procedure, they're automatically available to all procedures.
The first procedure is the Window_OnLoad event handler:
Sub Window_OnLoad 'Can't set controls before page created
optNum.Item(0).Value = False 'Clear default selection
txtStatus.Value = "Your answer please!"
End Sub
Before you can set properties of a control, the control has to be loaded. And, if you want to set control properties during the initialization phase (such as, only once, when the page loads) you'll have to do so in the Window_OnLoad event, since if you execute them outside of any procedure, they'll be executed during the parse phase, before any controls are created.
To address a specific OptionButton in code, you need to use the Item property. The code in the Window_OnLoad event sets the Value property of the first OptionButton to False. Because OptionButtons begin with 0, that's the one that's set here. This code clears the first button. (By default, the first button in a group is selected, and since this example needs to have none selected, the first one has to be explicitly cleared.)
Before the procedure ends, it places "Your answer please!" into the Text control, so that the user will know to click one of the OptionButtons.
The CanTest event serves as the event handler for the OptionButtons:
The first thing this routine does is set the OkToTest variable to True. This variable is used in the cmdTest_OnClick event handler to determine whether or not an answer has been provided. (The CanTest procedure isn't called unless an OptionButton has been clicked. Because an OptionButton has been clicked, it's "OkToTest" the answer when the Test button is clicked.)
For information on For/Next loops, see Chapter 17, "VBScript Control of Flow and Error Handling."
For more information on OptionButton properties, see Chapter 20, "VBScript Forms, Controls, and Managing Transactions."
After setting the OkToTest variable, a For...Next loop counts through the OptionButtons, looking for the one that was selected. Because OptionButtons start with an Item of 0, the loop counts from 0 to 2. When it finds the selected OptionButton, it executes an Exit For statement to escape the loop. Because the loop counter (c) reflects the current OptionButton at the time it's found, it stores its number. For instance, if the second OptionButton (.Item(1)) has its .Checked property set to True, then the value of c will be 1.
After the loop finds the number of the selected OptionButton, the status string (the .Value property of txtStatus) is set to a string composed of the word "Answer," the number of the OptionButton, and the word "Selected."
Because OptionButtons start at 0, but answers on a quiz start at 1, the number in the string is offset by one (by adding c + 1).
After an answer is selected, the user will have to click the Test button to see if it's correct. The OnClick event for the cmdTest button directs the script to the FindAns routine to determine if the right answer was provided:
Sub cmdTest_OnClick
If OkToTest Then
FindAns
Else
txtStatus.Value = "Must Select an Answer!"
End If
End Sub
Before handing control over to the FindAns routine, cmdTest_OnClick checks the value of OkToTest. (This is the variable that is only set if the user first clicks an OptionButton.) If it's indeed ok to test, FindAns is called. If not, txtStatus is loaded with a warning to select an answer.
The FindAns routine does the actual testing:
Sub FindAns
Select Case c 'Test if it's the right answer
Case 0, 2
txtStatus.Value = "Wrong!"
Case 1
txtStatus.Value = "Correct!"
End Select
End Sub
A Select Case block tests the value of c against 0 and 2 (the incorrect answers), and 1 (the correct answer), and displays the appropriate message in the status Text control.
The Reset control is a special type of button control. When it's clicked, it clears the contents of the other controls. At the time this book goes to press, it has one event implemented: the OnClick event. (An OnFocus event is documented, but not working.)
The Submit control has one event: OnSubmit, which is covered under "Form Object" earlier in this chapter.
The Text and TextArea controls have OnFocus and OnBlur events. These correspond to GotFocus and LostFocus events in VB. Because the TextArea control can be considered a functional equivalent of a VB TextBox control with a Multiline property set to True, we examine the two of them together here.
At the time of this writing, the OnChange and OnSelect events are documented, but not implemented for the Text, TextArea, and Password controls. The OnChange event will fire when the contents of the control change, and the OnSelect event will fire when text is selected within the control.
Listing 18.8 Text and TextArea Events Example
The code in Listing 18.7 updates the display in a Text control (txtTest) whenever the OnFocus or OnBlur events occur in a TextArea control (txaTest).
In many situations, the HTML Intrinsic controls provide all the interactivity your applications require. For certain situations, however, you need features they do not provide. ActiveX controls provide specialized functionality that is not available via the Intrinsic controls.
When an Intrinsic control does the job, use it. The Intrinsic controls are general-purpose input and display controls; ActiveX controls are specialized controls. Each ActiveX control is unique, and is created with a specific purpose in mind. Many of them are quite complex, and require quite a bit of detailed study to use effectivelyùsome of them are essentially major applications disguised as "tools" that can be embedded in a container such as an HTML Layout Web page. Their power and flexibility aside, they require no less attention to detail and study than does a standalone program of a similar nature. Those developers who choose to learn the details of their tools are able to leverage them to great effect.
ActiveX controls are supplied by numerous vendors. Remember, the main usage distinction between ActiveX controls and HTML Intrinsic controls deal with declaration and naming of properties and events; the actual use in your script blocks is the same (in regards to event handling). The information provided earlier in this chapter for HTML controls also equally applies to ActiveX controls.
An understanding of event handling is necessary to make real use of VBS. The material presented in this chapter provides you with the mechanics involved in using event routines. The information presented in Part 4 of this book presumes an understanding of the material presented here, and goes on to teach you how to use that knowledge to create powerful script-enabled Internet applications.
| Previous Chapter | Next Chapter |
| Search | Table of Contents | Book Home Page | Buy This Book |
| Que Home Page | Digital Bookshelf | Disclaimer |
To order books from QUE, call us at 800-716-0044 or 317-361-5400.
For comments or technical support for our books and software, select Talk to Us.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.